<template>
  <u-popup mode="center" round="8" closeable :show="show" @open="open" @close="updateShow(false)">
    <view class="popup">
      <view class="text-center text-16 py-12">
        <text v-if="form.id">编辑地址</text>
        <text v-else>添加地址</text>
      </view>

      <scroll-view scroll-y style="max-height: 50vh; ">
        <u-form ref="uFormRef" label-position="left" :model="form" :rules="rules" label-width="60">
          <u-form-item label="姓名" prop="consignee" border-bottom required>
            <u-input v-model="form.consignee" placeholder="请输入收货人姓名" />
          </u-form-item>
          <u-form-item label="手机" prop="phone" border-bottom required>
            <u-input v-model="form.phone" maxlength="11" type="number" placeholder="请输入手机号码" />
          </u-form-item>
          <u-form-item label="省市区" prop="area_name" border-bottom class="relative" required @click="showArea = true">
            <u-input v-model="form.area_name" class="w-full" placeholder="请选择省市区" readonly />
            <view class="absolute-full" />
          </u-form-item>
          <u-form-item label="地址" prop="address" border-bottom required>
            <u-textarea v-model="form.address" placeholder="请输入详细地址" height="40" />
          </u-form-item>

          <u-form-item label="默认" prop="is_def" border-bottom>
            <u-switch
              v-model="form.is_def"
              size="24"
              :active-value="1"
              :inactive-value="0"
              @change="value=> form.is_def = value"
            />
            <text class="text-12 pl-10 text-tips">设置默认地址状态</text>
          </u-form-item>
        </u-form>
      </scroll-view>

      <view class="py-12 hair-t">
        <u-button text="保存" type="primary" @click="save" />
      </view>
    </view>

    <u-picker
      ref="uPickerRef"
      key-name="name"
      :show="showArea"
      :columns="areaColumns"
      @close="showArea = false"
      @cancel="showArea = false"
      @confirm="areaConfirm"
      @change="areaChange"
    />
  </u-popup>
</template>

<script setup>
import {
  ref,
  defineProps,
  defineEmits
} from 'vue'

import $ from '@/sheep'

const props = defineProps({
  show: Boolean,
  data: {
    type: Object,
    default: () => {}
  }
})
const emit = defineEmits(['update:show', 'done'])

const uFormRef = ref(null)
const uPickerRef = ref(null)
const showArea = ref(false)
const areaColumns = ref([])

const {
  form,
  assignForm
} = $.useForm({
  id: undefined,
  consignee: '',
  phone: '',
  address: '',
  area_code: '',
  area_name: '',
  is_def: 0
})

const rules = {
  consignee: [{
    required: true,
    message: '请输入收货人姓名'
  }],
  phone: [{
    required: true,
    message: '请输入手机号'
  },
  {
    pattern: /^1\d{10}$/,
    message: '请输入正确的手机号'
  }
  ],
  area_code: [{
    required: true,
    message: '请选择省市区'
  }],
  address: [{
    required: true,
    message: '请输入详细地址'
  }]
}

function updateShow(value = false) {
  emit('update:show', value)
}

function getList() {
  $.get('/city/list').then(res => {
    const areaList = $.utils.toTree(res.data)
    areaColumns.value = [areaList, areaList[0].children, areaList[0].children[0].children]
  })
}

function save() {
  uFormRef.value.validate().then(res => {
    $.post('/User/consigneeEdit', form, {
      isShop: 1
    }).then(res => {
      if (res.success) {
        updateShow(false)
        emit('done')
      }
      $.utils.toast('操作成功')
    })
  }).catch(err => {
    console.log(err)
  })
}

function open() {
  if (!areaColumns.value.length) {
    getList()
  }
  assignForm({
    ...form,
    ...props.data
  })
}

function areaChange({
  columnIndex,
  index
}) {
  // 当第一列值发生变化时，变化第二列(后一列)对应的选项
  const data = areaColumns.value[columnIndex][index].children
  if (columnIndex === 0) {
    areaColumns.value[1] = data
    areaColumns.value[2] = data[0].children

    uPickerRef.value.setColumnValues(1, data)
    uPickerRef.value.setColumnValues(2, data[0].children)
  } else if (columnIndex === 1) {
    areaColumns.value[2] = data
    uPickerRef.value.setColumnValues(2, data)
  }
}

function areaConfirm({ value }) {
  const area_code = []
  const area_name = []
  value.forEach(v => {
    area_code.push(v.citycode)
    area_name.push(v.name)
  })

  form.area_code = area_code.join('-')
  form.area_name = area_name.join('-')
  showArea.value = false
}
</script>

<style lang="scss">
	.popup {
		width: 620rpx;
		padding: 0 30rpx;
	}
</style>
